package rbac.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import rbac.dao.UserGroupDao;
import rbac.entity.RbacUserGroup;


/**
 * RBAC 用户组管理 DAO 实现类.
 * 
 * @author Huadi
 * @author Zoufengyang
 */
@Repository("userGroupDao")
public class UserGroupDaoImpl extends HibernateDaoSupport implements UserGroupDao {

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
    public RbacUserGroup getUserGroup(Integer id) {
        return (RbacUserGroup) getHibernateTemplate().get(RbacUserGroup.class, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
    public List<RbacUserGroup> getAllUserGroups() {
        Query query = getSession().getNamedQuery("rbacUserGroup.getAllRbacUserGroups");

        return query.list();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
    public void save(RbacUserGroup userGroup) {
        getHibernateTemplate().save(userGroup);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
    public void update(RbacUserGroup userGroup) {
        getHibernateTemplate().update(userGroup);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
    public void delete(Integer id) {
        // XXX: 删除关系表中的实体关系记录, 此处与实体表耦合.
        Query q = getSession().createSQLQuery("DELETE FROM t_rbac_user_group WHERE group_id = :id");
        q.setInteger("id", id);
        q.executeUpdate();
        Query query = getSession().getNamedQuery("rbacUserGroup.deleteRbacUserGroupById");
        query.setInteger("id", id);
        query.executeUpdate();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
    public void delete(RbacUserGroup userGroup) {
        Query query = getSession().createSQLQuery(
                "DELETE FROM t_rbac_user_group WHERE user_group_id = :id");
        query.setInteger("id", userGroup.getId());
        query.executeUpdate();
        getHibernateTemplate().delete(userGroup);
    }

}
